/**
   Copyright 2011 Фроловский А. В.

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.
   
   This file is a part of MyStats project
 */

package foo.mystats;

import java.text.DateFormat;
import java.text.NumberFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.TimeZone;

import org.achartengine.ChartFactory;
import org.achartengine.chart.PointStyle;
import org.achartengine.model.XYMultipleSeriesDataset;
import org.achartengine.renderer.XYMultipleSeriesRenderer;
import org.achartengine.renderer.XYSeriesRenderer;

import android.app.DatePickerDialog;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Color;
import android.graphics.Paint.Align;
import android.os.Bundle;
import android.support.v4.app.LoaderManager;
import android.support.v4.content.Loader;
import android.view.View;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.TextView;
import foo.mystats.model.DataType;
import foo.mystats.model.StatisticsModel;

public class StatisticsActivity extends BaseActivity implements LoaderManager.LoaderCallbacks<Cursor> {
  private long rowId;
  private String rowName;

  private StatisticsModel model;
  private Bundle rowInfo;

  private TextView minimum;
  private TextView maximum;
  private TextView average;
  private TextView totalNumber;
  private TextView number;
  private TextView perDay;
  private TextView numberOfDays;
  private Button firstDate;
  private Button lastDate;

  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    this.setContentView(R.layout.statistics);

    initViews();

    rowId = getIntent().getExtras().getLong("row_id");
    rowName = getIntent().getExtras().getString("row_name");

    this.setTitle(rowName);
  }

  public void initViews() {
    // rowName = (TextView) findViewById(R.id.stats_rowname);
    firstDate = (Button) findViewById(R.id.stats_firstdate_button);
    lastDate = (Button) findViewById(R.id.stats_lastdate_button);
    minimum = (TextView) findViewById(R.id.stats_minimum);
    maximum = (TextView) findViewById(R.id.stats_maximum);
    average = (TextView) findViewById(R.id.stats_average);
    totalNumber = (TextView) findViewById(R.id.stats_total_number);
    number = (TextView) findViewById(R.id.stats_number);
    perDay = (TextView) findViewById(R.id.stats_per_day);
    numberOfDays = (TextView) findViewById(R.id.stats_days);
  }

  public String getDateAsString(Date date) {
    if (date == null || date.getTime() == 0) {
      return "-";
    } else {
      DateFormat df = DateFormat.getDateInstance();
      df.setTimeZone(TimeZone.getTimeZone("GMT+00:00"));

      return df.format(date);
    }
  }

  public String getTimeAsString(Date time) {
    if (time == null || time.getTime() == 0) {
      return "-";
    } else {
      // do not need AM/PM here because it's a period of time, not the
      // time
      SimpleDateFormat df = new SimpleDateFormat("HH:mm");
      df.setTimeZone(TimeZone.getTimeZone("GMT+00:00"));

      return df.format(time);
    }
  }

  private String getValueAsString(Object value) {
    String result = "-";

    if (value == null || rowInfo == null) {
      return result;
    }

    switch (rowInfo.getInt("data_type")) {
      case DataType.INTEGER:
        result = NumberFormat.getInstance().format(((Integer) value).intValue());
        break;
      case DataType.REAL:
        result = NumberFormat.getInstance().format(((Double) value).doubleValue());
        break;
      case DataType.TIME:
        result = getTimeAsString((Date) value);
        break;
    }

    return result;
  }

  private DatePickerDialog.OnDateSetListener firstDateSetListener = new DatePickerDialog.OnDateSetListener() {
    public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
      GregorianCalendar gc = new GregorianCalendar();
      gc.setTimeZone(TimeZone.getTimeZone("GMT+00:00"));

      gc.set(Calendar.YEAR, year);
      gc.set(Calendar.MONTH, monthOfYear);
      gc.set(Calendar.DAY_OF_MONTH, dayOfMonth);

      model.setFirstDate(gc.getTime());
    }
  };

  private DatePickerDialog.OnDateSetListener lastDateSetListener = new DatePickerDialog.OnDateSetListener() {
    public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
      GregorianCalendar gc = new GregorianCalendar();
      gc.setTimeZone(TimeZone.getTimeZone("GMT+00:00"));

      gc.set(Calendar.YEAR, year);
      gc.set(Calendar.MONTH, monthOfYear);
      gc.set(Calendar.DAY_OF_MONTH, dayOfMonth);

      model.setLastDate(gc.getTime());
    }
  };

  public void onSetFirstDateClick(View v) {
    GregorianCalendar gc = new GregorianCalendar();
    gc.setTimeZone(TimeZone.getTimeZone("GMT+00:00"));
    gc.setTime(model.getFirstDate());

    DatePickerDialog dpd = new DatePickerDialog(this, firstDateSetListener,
        gc.get(Calendar.YEAR), gc.get(Calendar.MONTH), gc.get(Calendar.DAY_OF_MONTH));

    dpd.show();
  }

  public void onSetLastDateClick(View v) {
    GregorianCalendar gc = new GregorianCalendar();
    gc.setTimeZone(TimeZone.getTimeZone("GMT+00:00"));
    gc.setTime(model.getLastDate());

    new DatePickerDialog(this, lastDateSetListener, gc.get(Calendar.YEAR),
        gc.get(Calendar.MONTH), gc.get(Calendar.DAY_OF_MONTH)).show();
  }

  public void onShowChartClick(View v) {
    XYMultipleSeriesDataset dataset = model.getDataSet();

    if (rowInfo.getInt("data_type") != DataType.STRING) {
      if (dataset != null) {
        Intent intent = ChartFactory.getTimeChartIntent(this, model.getDataSet(),
            getRenderer(), null);
        startActivity(intent);
      } else {
        showAlert(R.string.msg_no_data_for_chart);
      }
    } else {
      showAlert(R.string.msg_no_chart_for_text);
    }
  }

  private XYMultipleSeriesRenderer getRenderer() {
    XYMultipleSeriesRenderer renderer = new XYMultipleSeriesRenderer();

    XYSeriesRenderer r = new XYSeriesRenderer();
    r.setColor(Color.WHITE);
    r.setPointStyle(PointStyle.CIRCLE);
    r.setLineWidth(0);
    r.setFillPoints(true);

    renderer.addSeriesRenderer(r);

    renderer.setShowGrid(true);
    renderer.setGridColor(Color.DKGRAY);

    renderer.setShowLegend(false);

    renderer.setMargins(new int[] { 5, 5, 70, 5 });
    renderer.setPointSize(5);

    renderer.setBackgroundColor(Color.BLACK);
    renderer.setXTitle("Date");
    renderer.setYTitle("Value");

    renderer.setYLabelsAlign(Align.LEFT);
    renderer.setShowAxes(false);

    return renderer;
  }

  @Override
  public Loader<Cursor> onCreateLoader(int id, Bundle args) {
    return DataListActivity.getLoader(this, this.rowId);
  }

  @Override
  public void onLoadFinished(Loader<Cursor> loader, Cursor cursor) {
    cursor.moveToFirst();
    while (cursor.moveToNext()) {
      // todo count average, min, max, etc.
    }
  }

  @Override
  public void onLoaderReset(Loader<Cursor> loader) {
    // TODO Auto-generated method stub

  }
}
